﻿using System;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace CIS.Extension
{
	public class MailSender : IDisposable
	{
		SmtpClient _smtp;

		public MailSender(string smtpServer)
		{
			_smtp = new SmtpClient(smtpServer);
		}

		public string SendMail(MailAddress from, MailMessage message, string password)
		{
			var str = string.Empty;
			try
			{
				ServicePointManager.ServerCertificateValidationCallback = delegate (object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
				{
					return true;
				};

				message.From = from;
				_smtp.Credentials = new NetworkCredential(from.Address, password);
				_smtp.EnableSsl = true;
				//_smtp.Port = 465;
				_smtp.Send(message);
				return string.Empty;
			}
			catch (SmtpException ex)
			{
				if (ex.StatusCode == SmtpStatusCode.TransactionFailed)
				{
					str = "邮件服务器异常，邮件发送失败！ ";
				}
				else if (ex.StatusCode == SmtpStatusCode.MailboxUnavailable)
				{
					str = "邮箱不正确，邮件发送失败！";
				}
				else if (ex.StatusCode == SmtpStatusCode.MailboxNameNotAllowed)
				{
					str = "密码不正确，邮件发送失败！";
				}
				else if (ex.StatusCode == SmtpStatusCode.GeneralFailure)
				{
					str = "网络异常，邮件发送失败！";
				}
				else
				{
					str = "邮件发送失败，请联系系统管理员！ ";
				}
			}
			catch (Exception ex)
			{
				str = "Error!";
			}

			return str;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (_smtp != null)
				{
					_smtp.Dispose();
				}
			}
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}
	}
}